package com.daxia.ogmall.web.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.Logs;
import com.daxia.ogmall.dto.BrandDTO;
import com.daxia.ogmall.dto.JsonResultDTO;
import com.daxia.ogmall.service.BrandService;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.QiniuUtils;
import com.daxia.ogmall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/brand", produces="text/html;charset=UTF-8")
public class AdminBrandController extends BaseController {

	@Autowired
	private BrandService brandService;

	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		if (id != null) {
			BrandDTO dto = brandService.load(id);
			map.put("n", dto);
		}
		return "admin/brand/brand_detail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save")
	
	public String save(BrandDTO dto, JsonResultDTO resultDTO) throws Exception {
		if (dto.getId() == null) {
			brandService.create(dto);
		} else {
			BrandDTO old = brandService.load(dto.getId());
			old.setName(dto.getName());
			old.setCode(dto.getCode());
			old.setImage(dto.getImage());
			old.setView3dURL(dto.getView3dURL());
			old.setSenceTravel(dto.getSenceTravel());
			old.setView3dImage(dto.getView3dImage());
			old.setHeadImage(dto.getHeadImage());
			old.setContent(dto.getContent());
			old.setRecommend(dto.getRecommend());
			brandService.updateAllFields(old);
		}
		return okAndClose(resultDTO);
	}

    
	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		brandService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	public String list(BrandDTO dto, Map<String, Object> map, Page page) {
		List<BrandDTO> dtos = brandService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/brand/brand_list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/datagrid")
    
    public String datagrid(BrandDTO dto, Map<String, Object> map, Page page) throws Exception {
        List<BrandDTO> dtos = brandService.find(dto, page);
        JSONArray jsonArray = new JSONArray();
        for (BrandDTO brand : dtos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", brand.getId());
            jsonObject.put("name", brand.getName());
            jsonObject.put("image", brand.getImage());
            jsonArray.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("total", page.getTotalRecords());
        json.put("rows", jsonArray);
        return json.toJSONString();
    }
	
	/**
	 * 第一行是表头。
	 * 第一列是工厂名称，第二列是品牌名称，第三列是品牌logo的文件名（不带.jpg后缀的文件名）
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("upload")
	public String upload(HttpServletRequest request) throws Exception {
		Logs.COMMON.debug("upload...");
		MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;  
        MultipartFile mf = mhs.getFile("file");
        Logs.COMMON.debug("mf: " + mf);
		brandService.doUpload(mf);
		return okAndClose(new JsonResultDTO());
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping("uploadImages")
	public String uploadImages(HttpServletRequest request) throws Exception {
		MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
		List<MultipartFile> mfList = mhs.getFiles("files");
		Logs.COMMON.debug(mfList.size());
		for (MultipartFile mf : mfList) {
			String originalFilename = mf.getOriginalFilename();
			String imageUrl = QiniuUtils.upload(mf.getBytes());
			String specCode = originalFilename.split("\\.")[0];
			BrandDTO query = new BrandDTO();
			query.setImportImageName(specCode);
			BrandDTO s = brandService.findOne(query);
			if (s != null) {
				BrandDTO p = brandService.load(s.getId());
				p.setImage(imageUrl);
				brandService.updateAllFields(p);
			}
		}
		return okAndClose(new JsonResultDTO());
	}
	

}
